package queue;

import java.util.Enumeration;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QBrowser implements MessageListener{
	
	private QueueSession session;
	private Queue queue;
	
	public QBrowser(String connectionFactory, String queueName) throws NamingException, JMSException{
		
		Context context = new InitialContext();
		QueueConnectionFactory factory = (QueueConnectionFactory)context.lookup(connectionFactory);
		QueueConnection connection = factory.createQueueConnection();
		connection.start();
		
		session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); 
		queue = (Queue)context.lookup(queueName);
		QueueReceiver receiver = session.createReceiver(queue);
		receiver.setMessageListener(this);
	}

	@Override
	public void onMessage(Message arg0) {

		try {
			QueueBrowser browser = session.createBrowser(queue);
			Enumeration e = browser.getEnumeration();
			while(e.hasMoreElements()){
				
				TextMessage message = (TextMessage)e.nextElement();
				System.out.println("检测到:" + message.getText());
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws NamingException, JMSException {
		
		QBrowser browser = new QBrowser("a", "b");
	}
}
